require("Scripts/Common/Class")
require("Scripts/Common/Utility")
require("Scripts/Common/Json")

LoopLinear = Class()

function LoopLinear:Ctor(loop_target, property, target_value, total_time, delay_time)
	self._target = loop_target
	self._target_value = target_value
	if total_time < 0 then total_time = 0 end
	self._total_time = total_time
	if delay_time < 0 then delay_time = 0 end
	self._total_delay_time = delay_time

	self._accumulate_time = 0
	self._accumulate_delay_time = 0
	if loop_target == nil or loop_target["Set"..property] == nil or loop_target["Get"..property] == nil then
		self._accumulate_time = self._total_time
		Sail_Log("LoopLinear create failed")
		return
	end

	self._get_function = loop_target["Get"..property]
	self._set_function = loop_target["Set"..property]
end

function LoopLinear:Reset()
	self._accumulate_time = 0
	self._accumulate_delay_time = 0
	self._init_value = nil
end

function LoopLinear:IsCompleted()
	return self._accumulate_time >= self._total_time
end

function LoopLinear:SetTime(time)
	if time <= 0 then return 0 end
	if time <= self._total_delay_time then
		self._accumulate_delay_time = time
		return 0
	end
	self._accumulate_delay_time = self._total_delay_time
	time = time - self._total_delay_time
	if time < self._total_time then
		self._accumulate_time = time
		if self._init_value == nil then self._init_value = self._get_function(self._target) end
		local current_value = (self._accumulate_time*self._target_value + (self._total_time - self._accumulate_time)*self._init_value) / self._total_time
		self._set_function(self._target, current_value)
		return 0
	end
	self._set_function(self._target, self._target_value)
	return time - self._total_time
end

function LoopLinear:Update(frame_time)
	if self._accumulate_delay_time < self._total_delay_time then
		self._accumulate_delay_time = self._accumulate_delay_time + frame_time
		if self._accumulate_delay_time <= self._total_delay_time then return end
		frame_time = self._accumulate_delay_time - self._total_delay_time
		self._accumulate_delay_time = self._total_delay_time
	end
	if self._init_value == nil then self._init_value = self._get_function(self._target) end
	self._accumulate_time = self._accumulate_time + frame_time
	if self._accumulate_time > self._total_time then self._accumulate_time = self._total_time end
	local current_value = (self._accumulate_time*self._target_value + (self._total_time - self._accumulate_time)*self._init_value) / self._total_time
	self._set_function(self._target, current_value)
end
